package com.spc.boot.common.security.entity;

import com.spc.boot.common.util.StringUtil;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 返回给前端的结果对象
 * 
 * @author ghliu
 *
 */
public class ResultMap extends HashMap<String, Object> {

	public ResultMap() {
		super.put("success", false);
		super.put("message", null);
		super.put("code", null);
		super.put("parameters", new HashMap<String, Object>());
	}

	public Boolean getSuccess() {
		return (Boolean) super.getOrDefault("success",false);
	}

	public void setSuccess(Boolean success) {
		super.put("success", success);
	}

	public String getMessage() {
		Object msg = super.get("message");
		return msg != null ? msg.toString():null;
	}

	public void setMessage(String message) {
		super.put("message", message);
	}

	public void setMessage(String message, String format) {
		super.put("message", String.format(format, message));
	}

	public String getCode() {
		return StringUtil.formatNullValue(super.get("code"),null);
	}

	public void setCode(String code) {
		super.put("code", code);
	}

	/**
	 * 返回结果如果需要其他参数，请在这里添加。
	 * 
	 * @return
	 */
	public Map<String, Object> getParameters() {
		if(!super.containsKey("parameters")){
			super.put("parameters", new HashMap<String, Object>());
		}
		return (Map<String, Object>) super.get("parameters");
	}

	public void setParameters(Map<String, Object> parameters) {
		super.put("parameters",parameters);
	}

	/**
	 * 封装动作，并返回 result 对象。
	 * 
	 * @param action
	 * @return
	 */
	public static ResultMap wrap(Action action) {
		ResultMap result = new ResultMap();
		try {
			action.invoke(result);
			result.setSuccess(true);
		} catch (Exception e) {
			result.setSuccess(false);
			if (StringUtils.isEmpty(result.getMessage())) {
				result.setMessage(e.getMessage());
			}
		}
		return result;
	}

	public static interface Action {
		void invoke(ResultMap result) throws Exception;
	}

    public static ResultMap success(Map<String, Object> parameters) {
		ResultMap result = new ResultMap();
        result.setSuccess(true);
        result.setParameters(parameters);
        return result;
    }

    public static ResultMap success(String message) {
		ResultMap result = new ResultMap();
        result.setSuccess(true);
        result.setMessage(message);
        return result;
    }

    public static ResultMap error(String message) {
		ResultMap result = new ResultMap();
        result.setMessage(message);
        return result;
    }

}
